package com.maotai.bl.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.maotai.bl.bean.BLWebCookie;

public class BLHttpClientUtil {
	private static BLHttpClientUtil instance = null;
	
	private BLHttpClientUtil() {
	}

	public static BLHttpClientUtil getInstance() {
		if (instance == null) {
			instance = new BLHttpClientUtil();
		}
		return instance;
	}
	public byte[] getImage(String httpUrl,BLWebCookie mwc, String imagereferer) throws Exception {
		HttpGet httpGet = new HttpGet(httpUrl);
		httpGet = setHttpGetDataHeader(httpGet,mwc,imagereferer);
		return sendHttpGetImage(httpGet,mwc);
	}
	private HttpGet setHttpGetDataHeader(HttpGet httpGet,BLWebCookie mwc,String referer) {
		httpGet.addHeader("Accept",
				"image/webp,image/apng,image/*,*/*;q=0.8");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate, br");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpGet.addHeader("Connection", "keep-alive");
		httpGet.addHeader("Host", "passport.bl.com");
		httpGet.addHeader("Referer", referer);
		httpGet.addHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
		
		String cookie = "";
		if(mwc.get__bl_test_id_()!=null && !"".equals(mwc.get__bl_test_id_())){
			cookie += "__bl_test_id_="+mwc.get__bl_test_id_()+";";
		}
		if( !"".equals(cookie)){
			httpGet.addHeader("Cookie",cookie);
		}
		return httpGet;
	}
	private byte[] sendHttpGetImage(HttpGet httpGet,BLWebCookie mwc) throws Exception {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		byte[] retByte ;
		httpClient = HttpClients.createDefault();
		
//		httpGet.setConfig(config);
		response = httpClient.execute(httpGet);
		Header[] headers = response.getAllHeaders();
		if(headers!=null&&headers.length>0){
        	for (Header hea : headers) {
				if(hea.getName().contains("Set-Cookie")||hea.getName().contains("set-cookie")){
					String temp = hea.getValue();
					if(temp.contains("__bl_test_id_")){
						mwc.set__bl_test_id_(temp.split(";")[0].split("=")[1]);
					}
				}
			}
        }
		entity = response.getEntity();
		retByte = toByteArray(entity.getContent());
		
		try {
			if (response != null) {
				response.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}
		} catch (Exception e) {
		}

		return retByte;
	}
	public BLWebCookie sendHttpPostProxy(String httpUrl,BLWebCookie mwc, Map<String, String> maps,RequestConfig requestConfig, String referer) throws Exception {  
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost = setHttpPostHeader(httpPost,mwc,referer);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        if(maps!=null && maps.size()>0){
        	for (String key : maps.keySet()) {  
                nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));  
        return sendHttpPostProxy(httpPost,mwc,requestConfig);  
    }
	private HttpPost setHttpPostHeader(HttpPost httpPost, BLWebCookie mwc ,String referer) throws Exception {
		httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.addHeader("Connection", "keep-alive");
		httpPost.addHeader("Accept","*/*");
		httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.addHeader("Connection", "keep-alive");
		httpPost.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		httpPost.addHeader("Origin","https://reg.bl.com");
		httpPost.addHeader("Referer",referer);
		httpPost.addHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
		
		String cookie = "";
		if(mwc.get__bl_test_id_()!=null && !"".equals(mwc.get__bl_test_id_())){
			cookie += "__bl_test_id_="+mwc.get__bl_test_id_()+";";
		}
		if(mwc.get__mn()!=null && !"".equals(mwc.get__mn())){
			cookie += "__mn="+mwc.get__mn()+";";
		}
		if(mwc.get__s_id()!=null && !"".equals(mwc.get__s_id())){
			cookie += "__s_id="+mwc.get__s_id()+";";
		}
		if(mwc.get_m_e_p()!=null && !"".equals(mwc.get_m_e_p())){
			cookie += "_m_e_p="+mwc.get_m_e_p()+";";
		}
		if(mwc.get_m_t_i()!=null && !"".equals(mwc.get_m_t_i())){
			cookie += "_m_t_i="+mwc.get_m_t_i()+";";
		}
		if(mwc.getBlsValue1()!=null && !"".equals(mwc.getBlsValue1())){
			cookie += "blsValue1="+mwc.getBlsValue1()+";";
		}
		if(mwc.getBlsValue2()!=null && !"".equals(mwc.getBlsValue2())){
			cookie += "blsValue2="+mwc.getBlsValue2()+";";
		}
		if(mwc.getBlsValue3()!=null && !"".equals(mwc.getBlsValue3())){
			cookie += "blsValue3="+mwc.getBlsValue3()+";";
		}
		if( !"".equals(cookie)){
			httpPost.addHeader("Cookie",cookie);
		}
		return httpPost;
	}
	private BLWebCookie sendHttpPostProxy(HttpPost httpPost,BLWebCookie mwc,RequestConfig config) throws Exception{  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;
		String return_str = null;
        httpClient = HttpClients.createDefault(); 
        if(config!=null)
        	httpPost.setConfig(config);  
        response = httpClient.execute(httpPost); 
        Header[] headers = response.getAllHeaders();
        entity = response.getEntity();
		return_str = EntityUtils.toString(entity, "UTF-8");
		mwc.setContent(return_str);
		//System.out.println(return_str);
        if(headers!=null&&headers.length>0){
        	for (Header hea : headers) {
        		if(hea.getName().contains("Set-Cookie")||hea.getName().contains("set-cookie")){
					String temp = hea.getValue();
					if(temp.contains("__bl_test_id_")){
						mwc.set__bl_test_id_(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("__mn")){
						mwc.set__mn(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("__s_id")){
						mwc.set__s_id(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("_m_e_p")){
						mwc.set_m_e_p(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("_m_t_i")){
						mwc.set_m_t_i(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("blsValue1")){
						mwc.setBlsValue1(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("blsValue2")){
						mwc.setBlsValue2(temp.split(";")[0].split("=")[1]);
					}else if(temp.contains("blsValue3")){
						mwc.setBlsValue3(temp.split(";")[0].split("=")[1]);
					}
					
				}
			}
        }
        if (response != null) {  
            response.close();  
        }  
        if (httpClient != null) {  
            httpClient.close();  
        }  
        return mwc;  
    } 
	public static byte[] toByteArray(InputStream input) throws IOException {
	    ByteArrayOutputStream output = new ByteArrayOutputStream();
	    byte[] buffer = new byte[4096];
	    int n = 0;
	    while (-1 != (n = input.read(buffer))) {
	        output.write(buffer, 0, n);
	    }
	    return output.toByteArray();
	}
}